package chapter5.homework.heima.Q3updateFiles;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @Project ：learn_java
 * @File ：Client.java
 * @IDE ：IntelliJ IDEA
 * @Author ：自由如风间
 * @Date ：2025/3/16 11:21
 * @Description ：
 * 服务器：接收客户端上传的文件，上传完毕之后给出反馈
 * 客户端：将本地文件上传到服务器，接收服务器的反馈
 */

public class Client {
    public static void main(String[] args) throws IOException {

        String localhost = InetAddress.getLocalHost().getHostAddress();
        Socket socket = getSocket(localhost);

        // 读取服务器的反馈信息
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String line = br.readLine();
        System.out.println(line);

        // 释放资源
        socket.close();
    }

    // idea生成的提取方法
    private static Socket getSocket(String localhost) throws IOException {
        // samePort表示客户端和服务器都使用相同的一个端口。
        int samePort = 10086;
        Socket socket = new Socket(localhost, samePort);

        // 需要上传文件的路径
        String updateFileDir = "G:\\codes\\learn_java\\images\\aoa.webp";

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(updateFileDir));
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());

        byte[] bytes = new byte[1024];
        int len;
        while ((len = bis.read(bytes)) != -1) {
            bos.write(bytes, 0, len);
        }

        bos.flush();
        // 往服务器写出结束标记
        socket.shutdownOutput();
        return socket;
    }
}
